package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.PageResult;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public R login(Employee employee) {
        if (employee == null) {
            return R.error("参数非法");
        }

        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        //Employee employee1 = employeeMapper.selectOne(wrapper);
        Employee employee1 = this.getOne(wrapper);
        if (employee1 == null) {
            return R.error("该用户不存在");
        }
        if (!employee1.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        if (employee1.getStatus() != 1) {
            return R.error("员工已禁用");
        }
        return R.success(employee1);
    }

    @Override
    public R findPage(Integer page, Integer pageSize, String name) {

        if (null != name) {
            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(Employee::getUsername, name);
            Page<Employee> p = new Page<>(page, pageSize);
            Page<Employee> employeePage = employeeMapper.selectPage(p, wrapper);
            long total = employeePage.getTotal();
            PageResult pageResult = new PageResult(total, employeePage.getRecords());
            return R.success(pageResult);
        }
        Page<Employee> p = new Page<>(page, pageSize);
        Page<Employee> employeePage = employeeMapper.selectPage(p, null);
        long total = employeePage.getTotal();
        PageResult pageResult = new PageResult(total, employeePage.getRecords());
        return R.success(pageResult);
    }

    @Override
    public R updateStatus(Employee employee) {
        if (employee == null) {
            return R.error("参数非法");
        }
        Employee employee1 = employeeMapper.selectById(employee.getId());
        if (employee1==null){
            return R.error("用户不存在");
        }
        employeeMapper.updateById(employee);
        return R.success("修改成功");
    }

}
